home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: news.kei.com!wang!news
- From: emild@cs.technion.ac.il (Kohn Emil Dan)
- Subject: Re: Reclaiming memory allocated recursively
- Organization: Technion, Israel Institute of Technology
- Date: Tue, 2 Jan 1996 18:23:47 GMT
- Message-ID: <Pine.SV4.3.91-heb-2.04.960102200600.6304B-100000@cs.technion.ac.il>
- References: <4c8f8q$ln9@yarrow.wt.com.au>
- Sender: news@wang.com
-
-
-
- On Tue, 2 Jan 1996, bruce varley wrote:
-
- > I'm using self-referential structures as described in K&R 6.5 (page
- > 130 in my version). The program runs 'forever', storing data in a
- > binary tree - a days worh of data is collected, then dumped, and the
- > whole process starts all over again. My question is: How can I
- > reclaim the memory that has been recursively allocated? Using the
- > same approach as creating the tree - ie..........
- >
- > struct node *freetree (struct node *p)
- > {
- > if (p != NULL)
- > {
- > freetree (p -> left) ;
- > free (p -> data_pointer) ;
- > freetree (p -> right) ;
- > }
- > return (0) ;
- > }
- >
- > seems unlikely to work, because the memory required to navigate
- > through the tree is being deallocated as the process proceeds. In
- > fact, the system crashes when I run the routine.
- >
- > Any assistance would be most appreciated.
- >
- > bvarley@yarrow.wt.com.au
- >
-
- Try this out:
-
- void freetree(struct node *p)
- {
-
- if(p!=NULL)
- {
- freetree(p -> left);
- free(p -> data_pointer);
- freetree(p -> right);
- free(p); /* You have to free the memory allocated to the node, too*/
- /* this seems to be the main problem with your code*/
- }
- }
- In order to reclaim the memory used by the tree, call freetree, with the
- root of your tree as a parameter.
-
- Don't forget to assign NULL to the root of the tree, after the call to
- freetree, otherwise, subsequent calls to the tree insertion function will
- cause your program to crash.
-
-
- Hope this helps.
-
- Best regards,
-
- Emil
-